<template>
  <div>
    <el-card style="margin-bottom: 20px">
      <!-- <MenuSelect @getClassfiyId="getClassfiyIds" :show="scence != 0" /> -->
      分类查询
      <el-select
        v-model="selectClassify"
        @change="selectByClassify"
        clearable
        placeholder="请选择"
      >
        <el-option
          v-for="(item, index) in goodsClassify"
          :key="index"
          :value="item.classify"
        >
        </el-option>
      </el-select>
      <span style="margin-left: 20px; margin-right: 10px">名称查询</span>
      <el-input
        v-model="goodName"
        placeholder="请输入内容"
        style="width: 200px; margin-right: 8px"
      ></el-input
      ><el-button type="primary" @click="search">搜索</el-button>
    </el-card>
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="showDialog"
      style="margin-bottom: 7px"
      >添加商品</el-button
    >
    <el-table style="width: 100%" border :data="goodsList">
      <el-table-column type="index" label="序号" width="100px" align="center">
      </el-table-column>
      <el-table-column prop="goodsName" label="名称" width="width">
      </el-table-column>
      <el-table-column prop="description" label="描述" width="width">
      </el-table-column>
      <el-table-column prop="imgFile" label="默认图片" width="120">
        <template slot-scope="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.imgFile[0]"
            :preview-src-list="row.imgFile"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="classify" label="类型" width="100px">
      </el-table-column>
      <el-table-column prop="price" label="价格(元)" width="100px">
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-sort-up"
            v-if="row.status == 0"
            @click="upSale(row)"
          ></el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-sort-down"
            v-else
            @click="downSale(row)"
          ></el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editGoodsInfo(row, $index)"
          ></el-button>
          <el-button
            type="info"
            size="mini"
            icon="el-icon-info"
            @click="getDetailInfo(row)"
          ></el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="deleteGoodInfo(row, $index)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getGoodsList"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      style="text-align: center; margin-top: 10px"
    >
    </el-pagination>

    <!-- 添加商品弹窗表单 -->
    <el-dialog
      :title="goodInfo.id ? '修改商品信息' : '添加商品'"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="goodInfo">
        <el-form-item label="商品名" label-width="80">
          <el-input v-model="goodInfo.goodsName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" label-width="80">
          <el-input
            v-model="goodInfo.description"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类" label-width="80">
          <el-select v-model="goodInfo.classify" placeholder="请选择">
            <el-option
              v-for="(item, index) in goodsClassify"
              :key="index"
              :value="item.classify"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格(元)" label-width="80">
          <el-input v-model="goodInfo.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品图" label-width="60px">
          <el-upload
            action="/goods"
            list-type="picture-card"
            name="file"
            :multiple="true"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :auto-upload="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="true"
            :on-change="changeImage"
            :file-list="fileList"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitGoodInfo">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleImg">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "good",
  data() {
    return {
      page: 1,
      limit: 5,
      total: 50,
      goodsClassify: [],
      selectClassify: "",
      goodsList: [],
      dialogFormVisible: false,
      type: 1, //0:添加商品,1:修改商品
      //弹窗表单数据
      goodInfo: {
        goodsName: "",
        description: "",
        price: "",
        classify: "",
      },
      dialogVisibleImg: false,
      dialogImageUrl: "",
      fileList: [],
      goodName: "", //商品名
      changeIndex: 0,
      loading: false,
      skuDetail: {},
      drawer: false,
    };
  },
  created() {
    // this.getGoodInfoList();
    this.getGoodsByPage();
    this.getClassify();
  },

  methods: {
    test(row) {
      console.log(row, "-------------------------");
    },

    //获取全部商品信息
    async getGoodInfoList() {
      let res = await this.$API.good.reqGetGoodInfo();
      this.goodsList = res.data;
      this.formatImageUrl();
    },
    //根据名称获取商品 (分页)
    async search() {
      this.selectClassify = "";
      if (this.goodName == "") {
        this.getGoodsByPage();
        return;
      }
      let res = await this.$API.good.reqGetGoodByGoodNamePage(
        this.page,
        this.limit,
        this.goodName
      );
      this.goodsList = res.data.records;
      this.formatImageUrl();
      this.total = res.data.total;
    },
    //获取商品分类
    async getClassify() {
      let res = await this.$API.good.reqGetGoodClassify();
      this.goodsClassify = res.data;
    },

    //分页获取商品
    async getGoodsByPage() {
      let res = await this.$API.good.reqGetGoodsByPage(this.page, this.limit);
      if (res.code === "200") {
        this.goodsList = res.data.records;
        this.formatImageUrl();
        this.total = res.data.total;
        // this.limit = res.data.size;
      }
    },
    //根据分类获取商品
    async selectByClassify() {
      this.goodName = "";
      if (this.selectClassify == "") {
        this.getGoodsByPage();
        return;
      }
      let res = await this.$API.good.reqGetGoodByClassifyPage(
        this.page,
        this.limit,
        this.selectClassify
      );
      if (res.code == "200") {
        this.goodsList = res.data.records;
        this.formatImageUrl();
        this.total = res.data.total;
      }
    },

    //分页器选择页码
    getGoodsList(pages = 1) {
      this.page = pages;
      if (this.selectClassify !== "") {
        this.selectByClassify();
      } else if (this.goodName !== "") {
        this.search();
      } else {
        this.getGoodsByPage();
      }
    },

    //切换每页显示数
    handleSizeChange(limits) {
      this.limit = limits;
      this.getGoodsList();
    },

    //弹窗确认按钮
    async submitGoodInfo() {
      let formData = new FormData();
      this.fileList.forEach((item) => {
        if (item.raw) {
          formData.append("file", item.raw);
        }
      });
      Object.entries(this.goodInfo).map(([key, value]) => {
        if (key == "imgFile") {
          value.forEach((item) => {
            if (!(typeof item == "string")) {
              formData.append("imgFile", item.url);
            } else {
              formData.append("imgFile", item);
            }
          });
          return;
        }
        formData.append(key, value);
      });
      if (this.type == 0) {
        let res = await this.$API.good.reqAddGoodInfo(formData);
        if (res.code === "200") {
          this.handleAvatarSuccess();
          this.getGoodsByPage();
          this.dialogFormVisible = false;
          this.goodInfo = {};
          this.fileList = [];
          this.$message({
            message: "添加成功",
            type: "success",
          });
        } else {
          this.$message({
            message: "添加失败",
            type: "error",
          });
        }
      } else {
        let res = await this.$API.good.reqUpdateGoodInfo(formData);
        if (res.code === "200") {
          Object.assign(this.goodsList[this.changeIndex], this.goodInfo);
          this.dialogFormVisible = false;
          this.getGoodsByPage();
          this.$message({
            message: "商品信息修改成功",
            type: "success",
          });
          this.fileList = [];
          this.goodInfo = {};
        } else {
          this.$message({
            message: "商品信息修改失败",
            type: "error",
          });
        }
      }
    },

    // 商品上架
    async upSale(row) {
      let res = await this.$API.good.reqUpdateGoodStatus(row.id);
      if (res.code == 200) {
        row.status = 1;
        this.$message({ type: "success", message: "上架成功" });
      }
    },
    // 商品下架
    async downSale(row) {
      let res = await this.$API.good.reqUpdateGoodStatus(row.id);
      if (res.code == 200) {
        row.status = 0;
        this.$message({ type: "success", message: "下架成功" });
      }
    },
    //删除商品
    async deleteGoodInfo(row, index) {
      this.$confirm(`是否删除${row.goodsName}该商品?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$API.good.reqDeleteGoodInfo(row.id);
          if (res.code === "200") {
            this.goodsList.splice(index, 1);
            this.$message({ type: "success", message: "删除成功" });
            this.getGoodsList(
              this.goodsList.length > 1 ? this.page : this.page - 1
            );
          } else {
            this.$message({ type: "success", message: "删除失败" });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.goodInfo.imgFile = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },

    changeImage(file, fileList) {
      this.fileList = fileList;
    },

    handleAvatarSuccess() {
      console.log("---------------");
    },

    beforeAvatarUpload(file) {
      console.log(file, "********************");
    },

    // 显示添加弹窗
    showDialog() {
      this.type = 0;
      this.dialogFormVisible = true;
    },

    //点击修改商品按钮事件
    editGoodsInfo(row, index) {
      row.imgFile.map((item) => {
        this.fileList.push({ url: item });
      });
      this.type = 1;
      this.changeIndex = index;
      Object.assign(this.goodInfo, row);
      this.dialogFormVisible = true;
    },
    //关闭弹窗
    closeDialog() {
      this.dialogFormVisible = false;
      this.goodInfo = {};
      this.fileList = [];
    },

    async getDetailInfo(row) {
      this.$message({
        message: "开发中...",
        type: "info",
      });
    },
    //格式化图片路径
    formatImageUrl() {
      this.goodsList.forEach((item) => {
        if (item.imgFile !== "" && item.imgFile !== null) {
          item.imgFile = item.imgFile
            .replace(/\[|\]/g, "")
            .replace(/\s+/g, "")
            .split(",");
          item.imgFile.forEach((i, index, arr) => {
            arr[index] = `http://localhost:8080/api/img/` + i;
          });
        }
      });
    },
  },
  mounted() {
    // this.getSkuList();
  },
};
</script>

<style>
/* .el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.el-carousel__button {
  width: 10px;
  height: 10px;
  background: pink;
  border-radius: 50%;
} */

/* 文件上传样式 */
/* .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
} */
</style>

<style scoped>
.el-col-5 {
  font-size: 18px;
  text-align: right;
  margin-bottom: 10px;
  margin-right: 15px;
}
</style>